import { defineStore } from 'pinia'
import { shopApi } from '@/api/shop'
import { ElMessage } from 'element-plus'

export const useShopStore = defineStore('shop', {
  state: () => ({
    // 店铺列表数据
    shops: [],
    // 当前选中的店铺
    currentShop: null,
    // 加载状态
    loading: false,
    // 分页状态
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0
    },
    // 筛选条件
    filterParams: {
      keyword: '', // 搜索关键词（店铺名称）
      recommendLevel: '', // 推荐等级筛选
      status: '', // 状态筛选
      category: '', // 分类筛选
      dateRange: [] // 创建时间范围
    },
    // 图片上传状态
    uploadLoading: false
  }),

  getters: {
    // 获取活跃店铺
    activeShops: (state) => state.shops.filter(shop => shop.status === 'active'),
    
    // 获取非活跃店铺
    inactiveShops: (state) => state.shops.filter(shop => shop.status === 'inactive'),
    
    // 按推荐等级分组的店铺
    shopsByRecommendLevel: (state) => {
      const grouped = {}
      state.shops.forEach(shop => {
        const level = shop.recommendLevel || 0
        if (!grouped[level]) {
          grouped[level] = []
        }
        grouped[level].push(shop)
      })
      return grouped
    },
    
    // 店铺统计信息
    shopStats: (state) => {
      const stats = {
        total: state.shops.length,
        active: 0,
        inactive: 0,
        byLevel: { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 }
      }
      
      state.shops.forEach(shop => {
        stats[shop.status] = (stats[shop.status] || 0) + 1
        if (shop.recommendLevel >= 1 && shop.recommendLevel <= 5) {
          stats.byLevel[shop.recommendLevel]++
        }
      })
      
      return stats
    }
  },

  actions: {
    // 获取店铺列表
    async fetchShops(params = {}) {
      this.loading = true
      try {
        const queryParams = {
          page: this.pagination.current,
          pageSize: this.pagination.pageSize,
          ...this.filterParams,
          ...params
        }
        
        const response = await shopApi.getShops(queryParams)
        this.shops = response.data || []
        this.pagination.total = response.total || 0
        
        return response
      } catch (error) {
        console.error('获取店铺列表失败:', error)
        ElMessage.error('获取店铺列表失败')
        throw error
      } finally {
        this.loading = false
      }
    },

    // 创建店铺
    async createShop(shopData) {
      try {
        const response = await shopApi.createShop(shopData)
        
        // 刷新店铺列表
        await this.fetchShops()
        
        ElMessage.success('店铺创建成功')
        return response
      } catch (error) {
        console.error('创建店铺失败:', error)
        ElMessage.error('创建店铺失败')
        throw error
      }
    },

    // 更新店铺信息
    async updateShop(id, shopData) {
      try {
        const response = await shopApi.updateShop(id, shopData)
        
        // 更新本地店铺数据
        const index = this.shops.findIndex(shop => shop.id === id)
        if (index !== -1) {
          this.shops[index] = { ...this.shops[index], ...shopData }
        }
        
        ElMessage.success('店铺信息更新成功')
        return response
      } catch (error) {
        console.error('更新店铺失败:', error)
        ElMessage.error('更新店铺失败')
        throw error
      }
    },

    // 删除店铺
    async deleteShop(id) {
      try {
        await shopApi.deleteShop(id)
        
        // 从本地数据中移除店铺
        this.shops = this.shops.filter(shop => shop.id !== id)
        this.pagination.total -= 1
        
        ElMessage.success('店铺删除成功')
      } catch (error) {
        console.error('删除店铺失败:', error)
        ElMessage.error('删除店铺失败')
        throw error
      }
    },

    // 批量删除店铺
    async batchDeleteShops(shopIds) {
      try {
        await shopApi.batchDeleteShops(shopIds)
        
        // 从本地数据中移除店铺
        this.shops = this.shops.filter(shop => !shopIds.includes(shop.id))
        this.pagination.total -= shopIds.length
        
        ElMessage.success(`成功删除 ${shopIds.length} 个店铺`)
      } catch (error) {
        console.error('批量删除店铺失败:', error)
        ElMessage.error('批量删除店铺失败')
        throw error
      }
    },

    // 上传店铺图片
    async uploadShopImage(file, shopId = null) {
      this.uploadLoading = true
      try {
        const formData = new FormData()
        formData.append('file', file)
        if (shopId) {
          formData.append('shopId', shopId)
        }
        
        const response = await shopApi.uploadImage(formData)
        
        ElMessage.success('图片上传成功')
        return response
      } catch (error) {
        console.error('图片上传失败:', error)
        ElMessage.error('图片上传失败')
        throw error
      } finally {
        this.uploadLoading = false
      }
    },

    // 删除店铺图片
    async deleteShopImage(imageId, shopId) {
      try {
        await shopApi.deleteImage(imageId)
        
        // 更新本地店铺数据，移除图片
        const shopIndex = this.shops.findIndex(shop => shop.id === shopId)
        if (shopIndex !== -1) {
          this.shops[shopIndex].images = this.shops[shopIndex].images.filter(
            img => img.id !== imageId
          )
        }
        
        ElMessage.success('图片删除成功')
      } catch (error) {
        console.error('删除图片失败:', error)
        ElMessage.error('删除图片失败')
        throw error
      }
    },

    // 更新店铺状态
    async updateShopStatus(id, status) {
      try {
        await shopApi.updateShopStatus(id, status)
        
        // 更新本地店铺状态
        const index = this.shops.findIndex(shop => shop.id === id)
        if (index !== -1) {
          this.shops[index].status = status
        }
        
        ElMessage.success('店铺状态更新成功')
      } catch (error) {
        console.error('更新店铺状态失败:', error)
        ElMessage.error('更新店铺状态失败')
        throw error
      }
    },

    // 按推荐等级筛选店铺
    async filterByRecommendLevel(level) {
      this.filterParams.recommendLevel = level
      this.pagination.current = 1
      await this.fetchShops()
    },

    // 按状态筛选店铺
    async filterByStatus(status) {
      this.filterParams.status = status
      this.pagination.current = 1
      await this.fetchShops()
    },

    // 搜索店铺
    async searchShops(keyword) {
      this.filterParams.keyword = keyword
      this.pagination.current = 1
      await this.fetchShops()
    },

    // 综合筛选店铺
    async filterShops(filters) {
      this.filterParams = { ...this.filterParams, ...filters }
      this.pagination.current = 1
      await this.fetchShops()
    },

    // 重置筛选条件
    resetFilterParams() {
      this.filterParams = {
        keyword: '',
        recommendLevel: '',
        status: '',
        category: '',
        dateRange: []
      }
    },

    // 设置分页参数
    setPagination(pagination) {
      this.pagination = { ...this.pagination, ...pagination }
    },

    // 设置当前店铺
    setCurrentShop(shop) {
      this.currentShop = shop
    },

    // 清空当前店铺
    clearCurrentShop() {
      this.currentShop = null
    }
  }
})